package org.apache.lucene.ocean.database;

import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.apache.lucene.ocean.Index.IndexSnapshot;
import org.apache.lucene.ocean.util.Timeout;

/**
 * Holds the cached data for a key, generates the data using a lock.
 */
// TODO: add timestamp to remove when too old
public class CacheData<V> {
  protected ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
  protected V object;
  protected CacheKey<V> cacheKey;
  
  public CacheData(CacheKey<V> cacheKey) {
    this.cacheKey = cacheKey;
  }
  
  public CacheData(CacheKey<V> cacheKey, V object) {
    this.cacheKey = cacheKey;
    this.object = object;
  }
  
  public V getObject() {
  	return object;
  }
  
  public V get(IndexSnapshot indexSnapshot, Timeout timeout) throws Exception {
    lock.readLock().lock();
    try {
      if (object != null) return object;
    } finally {
      lock.readLock().unlock();
    }
    lock.writeLock().lock();
    try {
      if (object != null) return object;
      object = cacheKey.createObject(indexSnapshot, timeout);
      return object;
    } finally {
      lock.writeLock().unlock();
    }
  }
}
